package com.ymm.system.core.facade;

import com.ymm.system.api.constants.CargoEntity;
import com.ymm.system.api.constants.LltorderEntity;
import com.ymm.system.api.constants.TradeEntity;
import com.ymm.system.api.dto.DriverGrabDTO;
import com.ymm.system.api.facade.SystemGenerateOrderTradeService;
import com.ymm.system.api.utils.*;
import com.ymm.system.core.constants.OpsPersonTypeEnum;
import com.ymm.system.core.mq.sender.OrderCreateMsgSender;
import com.ymm.system.dao.mapper.CargoMapper;
import com.ymm.system.dao.mapper.LltorderMapper;
import com.ymm.system.dao.mapper.TradeMapper;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * @Author zikang.yao
 * @Description TODO
 * @Date 2022/8/3 15:32
 * @Version 1.0
 */

/**
 * 生成订单，订单调用运单
 */
@Service(version = "server")
@Slf4j
@Component
public class SystemGenerateOrderTradeServiceImpl implements SystemGenerateOrderTradeService {

    @Resource
    private CargoMapper cargoMapper;

    @Resource
    private TradeMapper tradeMapper;

    @Resource
    private LltorderMapper lltorderMapper;

    @Resource
    private OrderCreateMsgSender orderCreateMsgSender;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Result generateOrder(DriverGrabDTO driverGrabDTO) {
        Long cargoId = driverGrabDTO.getCargoId();
        Long driverId = driverGrabDTO.getDriverId();
        String searchInfo = "pushingCargo" + cargoId;
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        if (valueOperations.get(searchInfo) != null) {
            if (valueOperations.get(searchInfo).equals(driverId.toString())) {
                Result<Boolean> grabResult = generateOrderandTrade(driverGrabDTO);
                if (grabResult.isSuccess()) {
                    redisTemplate.delete("pushingDriver" + driverId);
                    redisTemplate.delete("pushingCargo" + cargoId);
                    redisTemplate.delete("cargoache" + cargoId.toString());
                }
                return grabResult;
            } else {
                log.info("当前货源不存在指定司机为" + valueOperations.get(searchInfo) + "   抢单司机为" + driverId);
                return Result.fail(false, ResultCodeEnum.PARAM_ERROR.getCode(), "当前货源不存在");
            }
        } else {
            //当前单不是派单，去抢单
            return generateOrderandTrade(driverGrabDTO);
        }
    }

    public Result<Boolean> generateOrderandTrade(DriverGrabDTO driverGrabDTO) {
        Long cargoId = driverGrabDTO.getCargoId();
        CargoEntity cargoEntity = cargoMapper.getCargoDetailsById(cargoId);
        TradeEntity tradeEntity = generateTrade(driverGrabDTO);
        if (tradeEntity == null) {
            log.info("当前货源不存在");
            log.info(driverGrabDTO.getDriverId()+"抢单失败");
            return Result.fail(false);
        }
        LltorderEntity lltorderEntity = new LltorderEntity();
//        lltorderEntity.setOrderId(Long.valueOf(0));
        lltorderEntity.setTradeId(tradeEntity.getTradeId());
        lltorderEntity.setDriverId(driverGrabDTO.getDriverId());
        lltorderEntity.setShipperId(cargoEntity.getShipperId());
        lltorderEntity.setOrderShipperState(OrderStatusEnum.ONGOING.getCode());
        lltorderEntity.setCargoId(cargoId);
        lltorderEntity.setOrderCreateDate(new Date());
        lltorderEntity.setOrderUpdateDate(new Date());
        lltorderEntity.setOrderPrice(cargoEntity.getCargoPrice());
        lltorderMapper.insertNewOrder(lltorderEntity);

        //给货主后端发消息
        try {
            orderCreateMsgSender.send(lltorderEntity.getOrderId(), cargoEntity.getShipperId(), lltorderEntity.getDriverId(), cargoEntity.getCargoId(), OpsPersonTypeEnum.DRIVER.getCode(), driverGrabDTO.getDriverId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info(driverGrabDTO.getDriverId()+"抢单成功");
        return Result.success(true);
    }

    private TradeEntity generateTrade(DriverGrabDTO driverGrabDTO) {
        Integer state = cargoMapper.updateCargoStateFromTo(driverGrabDTO.getCargoId(), CargoStatusEnum.ON_SHLFE.getCode(), CargoStatusEnum.HOLDING.getCode());
        System.out.println("state:"+state);
        if (state == 0) {
            return null;
        }
        TradeEntity tradeEntity = new TradeEntity();
//        tradeEntity.setTradeId(Long.valueOf(0));
        tradeEntity.setDriverLocation(driverGrabDTO.getDriverLocation());
        tradeEntity.setTradeDriverState(TradeCodeEnum.TO_LOADING_PLACE.getCode()); //生成运单，初始状态为空
        tradeEntity.setTradeCreateTime(new Date());
        tradeEntity.setTradeUpdateTime(new Date());
        tradeMapper.insertNewTrade(tradeEntity);
        return tradeEntity;
    }
}

